import { ref } from 'vue'
import { defineStore } from 'pinia'
import { base64Encode, base64Decode, cpjsDecode, cpjsEncode } from '../utils/utils'
import type { menu, route } from '../dataType/menu'
import { useRouter } from "vue-router";
import dayjs, { Dayjs } from 'dayjs';

export const useCounterStore = defineStore('counter', () => {
    const menu = ref<menu[]>([]) // 菜单出局
    // 面包屑数据
    const crumbs = ref<route[]>([
        { title: '首页', name: 'home', path: '/home', freeze: true }
    ])
    const topLevel = ref(false) // 顶级路由
    const currentRoute = ref<route>({
        path: '',
        name: ''
    }) // 当前打开路由
    const selectCrumbs = ref<route>({ title: '首页', name: 'home', path: '/home' })

    // 主播播放列表数据
    const liveData = ref<any>([])
    const router:any = useRouter()
    // const doubleCount = computed(() => count.value * 2)
    const  webSocketList = ref({
        bizType: null,
        content: '',
        name: '',
        types: null,
        id: '',
        remindLevel: 0,
        senderId: null,
        type: 1,
        userId: null
    })
     // 获取消息websocket
    const handleData = (res:any) => {
        console.log('websocket handleData',res)
        webSocketList.value.content = ''
        webSocketList.value.name = ''
        webSocketList.value.userId = null
        webSocketList.value.types = null
        let data = Object.assign(webSocketList.value,res)
        WEBSOCKET_LIST(data)
    }

    const WEBSOCKET_LIST = (data:any)  => {
        console.log('WEBSOCKET_LIST',data)
        webSocketList.value = data
    }
    // 设置menu数据
    function setMent(value: menu[]) {
        menu.value = value
    }

    // 设置当前打开路由
    const setCurrentRoute = (value: route) => {
        currentRoute.value = value
    }

    // 设置当前选择的菜单 
    const setSelectCrumbs = (value: route) => {
        let type: boolean = true
        if (!value) return
        selectCrumbs.value = value
        crumbs.value.forEach((v: route) => {
            if (v.name == value.name) {
                type = false
            }
        })
        if (type) {
            crumbs.value.push(value)
        }
    }

    // 获取用户信息
    const getLoginInfo = () => {
        const userinfo = localStorage.getItem('userinfo')
        let u = {}
        if (userinfo) u = JSON.parse(userinfo)
        return u
    }

    // 获取token
    const getLogToken = () => {
        const token = localStorage.getItem('token')
        let u = {}
        if (token) u = token
        return u
    }

    // 主播播放列表数据
    const setLiveData = (arr: any) => {
        liveData.value = arr
    }

    // 获取基础config数据
    const getConfig = () => {
        let str = localStorage.cg_str
        if (str) {
            str = base64Decode(str)
            str = cpjsDecode(str)
            return JSON.parse(str.replace(/[^\x20-\x7E]/g, ''))
        } else {
            return ''
        }
    }

    // 获取localStorage数据
    const getLocalStorage = ({ key, type, state }: { key: any, type?: number, state?: number }) => {
        // type 0: 不加密 1: base64加密  默认0
        // state 0: 不是对象  1: 对象  默认0
        let str = localStorage[key]
        if (str) {
            if (type == 1) {
                str = base64Decode(str)
            }
            if (state == 1) {
                str = JSON.parse(str)
            }
            return str
        } else {
            return {
                agora: {},
                im: {},
            }
        }
    }
    // 退出登录
    const Logout = () => {
        localStorage.clear();
        // window.location.reload()
        // router.replace('/home'); // 或者其他页面
    }

    // 时间戳转日期
    const timestampChangDate = (val: any) => {
        if (!val) return
        const date = new Date(val)
        const y = date.getFullYear()
        const m = date.getMonth() + 1
        const d = date.getDate()
        const _h = date.getHours()
        const _m = date.getMinutes()
        const _s = date.getSeconds()
        return `${y}-${m < 10 ? `0${m}`:m}-${d < 10 ? `0${d}`:d} ${_h < 10 ? `0${_h}`:_h}:${_m < 10 ? `0${_m}`:_m}:${_s < 10 ? `0${_s}`:_s}`
    }
    // 日期转时间戳
    const getTimestamp = (val: any) => {
        const date = new Date(val); // 使用ISO格式或任何有效的日期字符串
        return date.getTime() / 1000; // 或者 date.valueOf()
    }

    // 正则表达式用于每三位添加一个逗号
    const formatNumber = (num: any) => {
       return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };
    const setConnected = ref(false) // 是否连接成功
    // websocket连接成功
    const connect = () => {
        // 连接成功后，将 isConnected 状态设置为 true
        setConnected.value = true
    }
    const disconnect = () => {
        // 断开连接或退出登录时，将 isConnected 状态设置为 false
        setConnected.value = false
    }

   /**
   * 
   * @param 公用 -- 时间选择控制大于当前 
   * @returns 
   */
    // 禁用日期的判断函数
    const disabledDate = (current: Dayjs): boolean => {
        const tenMinutesLater = dayjs().add(10, 'minute');
    //   console.log(tenMinutesLater,'tenMinutesLater', dayjs(current).isBefore(tenMinutesLater))
    //   return current && dayjs(current).isBefore(tenMinutesLater);
        return  current && current < dayjs().endOf('day').subtract(1, 'days')
    };
    const rangeHours = (start:number, end:number, value:number, chooseday:number, day:number) => {
        const result = []
        if (chooseday === day) {
        for (let i = start; i < end; i++) {
            if (i < value) {
            result.push(i)
            }
        }
        }
        return result
    }
    const rangeMinutes = (start:number, end:number, value:number, chooseday:number, day:number, chooseh:number, h:number) =>{
        const result = []
        if (chooseday === day && chooseh === h) {
        for (let i = start; i < end; i++) {
            if (i < value) {
            result.push(i)
            }
        }
        }
        return result
    }
    const  rangeSeconds = (start:number, end:number, value:number, chooseday:number, day:number, chooseh:number, h:number, choosem:number, m:number) =>{
        const result = []
        if (chooseday === day && chooseh === h && choosem === m) {
        for (let i = start; i < end; i++) {
            if (i < value) {
            result.push(i)
            }
        }
        }
        return result
    }
    const disabledDateTime = (date:any) => {
        // 选中的时间
        const choosetime = dayjs(date).format('HH-mm-ss')
        const chooseday = parseInt(dayjs(date).format('YYYY-MM-DD').split('-')[2])
        const chooseh = parseInt(choosetime.split('-')[0])
        const choosem = parseInt(choosetime.split('-')[1])
        // 当前时间
        const nowtime = dayjs().format('HH-mm-ss')
        const day = parseInt(dayjs().format('YYYY-MM-DD').split('-')[2])
        let h = parseInt(nowtime.split('-')[0])
        let m = parseInt(nowtime.split('-')[1])
        const s = parseInt(nowtime.split('-')[2])
        // h = m + 10 > 60 ? h + 1 : h  // 当前时间选择加上10分钟
        // m = m + 10 > 60 ? (m + 10) - 60 : m + 10
        // console.log(date, choosetime,chooseday,chooseh,choosem,nowtime,day, h,m, s,'result')
        return {
            disabledHours: () => rangeHours(0, 24, h, chooseday, day),
            disabledMinutes: () => rangeMinutes(0, 60, m, chooseday, day, chooseh, h),
            disabledSeconds: () => rangeSeconds(0, 60, s, chooseday, day, chooseh, h, choosem, m)
        }
    }
    return {
        crumbs,
        menu,
        setMent,
        topLevel,
        currentRoute,
        setCurrentRoute,
        selectCrumbs,
        setSelectCrumbs,
        getLoginInfo,
        liveData,
        setLiveData,
        getLocalStorage,
        getConfig,
        timestampChangDate,
        getLogToken,
        formatNumber,
        setConnected,
        connect,
        disconnect,
        Logout,
        getTimestamp,
        webSocketList,
        handleData,
        disabledDate,
        disabledDateTime
    }
})
